package com.terrynoya.fight.timer
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.getTimer;

	[Event(name="time_snap_update", type="com.terrynoya.fight.timer.MTimerEvent")]
	public class TimerManager extends EventDispatcher
	{
		private var _timer:Timer;
		
		private var _lastTime:Number;
		
		private var _time:Number;
		
		public function TimerManager(fps:int = 30)
		{
			super();
			this._timer = new Timer(1000 / fps);
			this.addListeners();
		}
		
		public function start():void
		{
			this._timer.start();
			this._lastTime = getTimer();
			this._time = 0;
		}
		
		public function stop():void
		{
			this._timer.stop();
			this._time = 0;
		}
		
		private function addListeners():void
		{
			this._timer.addEventListener(TimerEvent.TIMER,onTimer);
		}
		
		private function onTimer(e:TimerEvent):void
		{
			var curr:Number = getTimer();
			var snap:Number = curr - this._lastTime;
			this._lastTime = curr;
			this._time += snap;
			this.dispachChangeEvt(snap,e);
		}
		
		private function dispachChangeEvt(snap:Number,timerEvt:TimerEvent):void
		{
			var evt:MTimerEvent = new MTimerEvent(MTimerEvent.TIME_SNAP_UPDATE);
			evt.snap = snap;
			evt.timerEvt = timerEvt;
			evt.time = this._time;
			this.dispatchEvent(evt);
		}
	}
}